require 'common'

class Group < ActiveRecord::Base

  belongs_to :site
  has_many :runners
  has_one :user

  validates_presence_of :name
  validates_presence_of :description
  validates_presence_of :site_id

  after_save :update_caches_for_site
  after_destroy :update_caches_for_site
  after_update :update_caches_for_site

  def percent_complete
    return calc_percent_complete(distance_cache, goal_cache)
  end

  def update_caches!
    distance = 0
    sessions = 0
    goal     = 0
    runners.each do |runner|
      distance = distance + runner.distance_cache
      sessions = sessions + runner.sessions_cache
      goal     = goal     + runner.goal
    end
    self.distance_cache = distance
    self.sessions_cache = sessions
    self.goal_cache     = goal
    self.runners_cache  = runners.count
    self.save!
    logger.debug{">>> UPDATED CACHES FOR GROUP: #{name}"}
  end

  def runners_within(index)
	  num = 0
	  self.runners.each { |r| if (r.distance_cache - index*26.2) < 26.2 and (r.distance_cache - index*26.2) >= 0: num+=1 end }
	  num
  end

  def runners_at(index)
	  num = self.runners_within(index)
	  if num > 1
		  num.to_s + ' runners'
	  elsif num == 1
		  '1 runner'
	  else
		  'zero runners'
	  end
  end

  private

    def update_caches_for_site
      site.update_caches!
    end

end
